(function () {
    angular.module('KtotApp').controller('WorkController', ['TaskService', function (taskService) {
        var self = this;        

        self.tasks = [];

        self.selectedIterationPath;

        self.selectedUserStory;

        self.availableIterationPaths = [];
        self.availableUserStories = [];

        self.getAvailableUserStories = function () {
            var items = Enumerable.From(self.tasks).Where(function (i) { return !self.selectedIterationPath || i.iterationPath === self.selectedIterationPath; })
                        .Select("$.userStory").Distinct().ToArray();

            self.getFilteredTasks();
            return items;
        };

        self.getAvailableIterationPaths = function () {            
            var items = Enumerable.From(self.tasks).Select("$.iterationPath").Distinct().ToArray();
            self.getFilteredTasks();
            return items;
        };

        self.getFilteredTasks = function () {
            if (self.groupedTasks && self.lastIterationPath == self.selectedIterationPath && self.lastUserStory == self.selectedUserStory) {
                return self.groupedTasks;
            }            

            self.lastIterationPath = self.selectedIterationPath;
            self.lastUserStory = self.selectedUserStory;

            var tasks = Enumerable.From(self.tasks)
                .Where(function (t) {
                    return (!self.selectedIterationPath || t.iterationPath === self.selectedIterationPath)
                            && (!self.selectedUserStory || t.userStory === self.selectedUserStory);

                }).ToArray();

            self.groupedTasks = taskService.groupTasks(tasks);

            return self.groupedTasks;
        };        

        self.loadTasks = function () {
            taskService.getTasks().then(function (result) {
                self.tasks = result;
                self.availableIterationPaths = self.getAvailableIterationPaths();
                self.availableUserStories = self.getAvailableUserStories();
            });            
        };
    }]);
})();